package edu.its.dreamteam.web.pages.admin;



import java.util.List;

import org.apache.tapestry.ValueEncoder;
import org.apache.tapestry.annotations.Component;
import org.apache.tapestry.annotations.Persist;
import org.apache.tapestry.corelib.components.Form;
import org.apache.tapestry.ioc.annotations.Inject;

import edu.its.dreamteam.daf.beans.Club;
import edu.its.dreamteam.daf.beans.Player;
import edu.its.dreamteam.daf.beans.Position;
import edu.its.dreamteam.daf.dao.IClubDao;
import edu.its.dreamteam.daf.dao.IPlayerDao;
import edu.its.dreamteam.daf.dao.IPositionDao;
import edu.its.dreamteam.web.base.SecureBasePage;
import edu.its.dreamteam.web.pages.model.ClubSelectionModel;
import edu.its.dreamteam.web.pages.model.PositionSelectionModel;
import edu.its.dreamteam.web.util.ClubValueEncoder;
import edu.its.dreamteam.web.util.PositionValueEncoder;

public class PlayerForm extends SecureBasePage{
	@Inject
	private IPlayerDao playerDao;
	@Inject
	private IPositionDao positionDao;
	@Inject
	private IClubDao clubDao;
	
	@Persist
	private Player player;	
	
	
	@Component
	private Form playerForm;	
	 
	private List<Position> positionList;	  
	private List<Club> clubList;

	private String idPlayer;
		
	public IClubDao getClubDao() {
		return clubDao;
	}
	public IPositionDao getPositionDao() {
		return positionDao;
	}	
	public IPlayerDao getPlayerDao() {
		return playerDao;
	}		
		
	public Player getPlayer() {
		return player;
	}
	public void setPlayer(Player player) {
		this.player = player;
	}
	
	
	public List<Position> getPositionList() {
		positionList = getPositionDao().queryForList("", "");
		return positionList;
	}
	public List<Club> getClubList() {
		clubList = getClubDao().queryForList("", "");
		return clubList;
	}
	
	
	public PositionSelectionModel getPositionSelectionModel() {		
		return new PositionSelectionModel(getPositionList());
	}
	public ValueEncoder<Position> getPositionValueEncoder(){
		return new PositionValueEncoder(getPositionList());
	} 
	
	public ClubSelectionModel getClubSelectionModel() {		
		return new ClubSelectionModel(getClubList());
	}
	public ValueEncoder<Club> getClubValueEncoder(){
		return new ClubValueEncoder(getClubList());
	} 
	
	void onPrepare(){
		if(player == null){
			player = new Player();
		}	
	}
	
	void cleanupRender() {
		setPlayer(null);	
	}
	
	void onActionFromClear(){
		setPlayer(null);
		playerForm.clearErrors();
	}
	
	Object onSuccessFromPlayerForm(){
		if(getPlayer().getIdPlayer()==null){
			getPlayerDao().insert(getPlayer());
		}else{
			getPlayerDao().update(getPlayer());			
		}
		setPlayer(null);		
		return PlayerGrid.class;
	}
	
	void onActivate(String idPlayer){
		this.idPlayer = idPlayer;
		setPlayer((Player) getPlayerDao().findByPrimaryKey(idPlayer));
	}
	
	String onPassivate(){ 
		return idPlayer;
	}	
	
}
